import { ComponentProps, FC, useState, useEffect } from "react";
import { BaseEventOrig, Input, View } from "@tarojs/components";
import { GStyleSheet } from "@/utils/DarkMode";
import { InputProps } from "@tarojs/components/types/Input";
// import { observer } from "mobx-react";
import Alert from ".";

const dstyles = GStyleSheet.create({
  input: {
    width: "100%",
    textAlign: "left",
  },
  inputWrapper: {
    padding: "20rpx",
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    borderBottomStyle: "solid",
  },
});

interface IProps
  extends Omit<ComponentProps<typeof Alert>, "content" | "onConfirm"> {
  defaultValue?: string;
  onConfirm?: (value?: string) => void;
  regular?: RegExp;
  maxLength?: number;
  placeholder?: string;
  keyboardType?: string;
}

const InputAlert: FC<IProps> = ({
  onConfirm,
  defaultValue,
  regular,
  placeholder,
  visible,
  maxLength,
  keyboardType,
  ...restProps
}) => {
  const [value, setValue] = useState(defaultValue);

  const styles = dstyles.useDynamicStyle();

  const handleConfirm = () => {
    onConfirm?.(value);
  };

  useEffect(() => {
    if (visible) {
      setValue(defaultValue);
    }
  }, [visible, defaultValue])

  const handleChangeText = (e: BaseEventOrig<InputProps.inputEventDetail>) => {
    const text = e.detail.value;
    if (regular && text) {
      if (regular.test(text)) {
        setValue(text);
      } else {
        setValue(value);
      }
    } else {
      setValue(text);
    }
  };

  return (
    <Alert
      content={
        <View style={styles.inputWrapper}>
          <Input
            style={styles.input}
            focus
            maxlength={maxLength}
            value={value}
            type={keyboardType}
            placeholder={placeholder}
            onInput={handleChangeText}
            holdKeyboard
          />
        </View>
      }
      onConfirm={handleConfirm}
      visible={visible}
      {...restProps}
    />
  );
};

export default InputAlert;
